package com.example.demo.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.dto.PassDto;
import com.example.demo.common.lang.Const;
import com.example.demo.common.lang.Result;
import com.example.demo.entity.SysRole;
import com.example.demo.entity.SysUser;
import com.example.demo.entity.SysUserRole;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 我的公众号：MarkerHub
 * @since 2024-05-18
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Resource
    BCryptPasswordEncoder bCryptPasswordEncoder;

    //查询
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result info(@PathVariable(name = "id") Long id) {
        SysUser user = sysUserService.getById(id);
        Assert.notNull(user, "找不到该管理员");
        List<SysRole> sysRole = sysRoleService.listRolesByUserId(id);
        user.setSysRoleList(sysRole);
        return Result.succ(user);
    }

    //
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result list(String name) {
        Page<SysUser> page = sysUserService.page(getPage(),
                new QueryWrapper<SysUser>().like(StrUtil.isNotBlank(name), "username", name));
        page.getRecords().forEach(e -> {
            e.setSysRoleList(sysRoleService.listRolesByUserId(e.getId()));
        });
        return Result.succ(page);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result save(@Validated @RequestBody SysUser sysUser) {

        sysUser.setCreated(LocalDateTime.now());
        sysUser.setStatu(Const.STATUS_ON);
        String password = bCryptPasswordEncoder.encode(Const.DEFAULT_PASSWORD);
        sysUser.setPassword(password);
        sysUser.setAvatar(Const.DEFAULT_AVATAR);
        sysUserService.save(sysUser);
        return Result.succ(sysUser);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result update(@Validated @RequestBody SysUser sysUser) {
        sysUser.setUpdated(LocalDateTime.now());
        sysUserService.updateById(sysUser);

        return Result.succ(sysUser);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@RequestBody Long[] ids) {
        sysUserService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id", ids));
        return Result.succ("");
    }

    @Transactional
    @GetMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result rolePerm(@PathVariable(name = "userId") Long userId, @RequestBody Long[] roleIds) {
        List<SysUserRole> sysUserRoles = new ArrayList<>();
        Arrays.stream(roleIds).forEach(e -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(e);
            sysUserRole.setUserId(userId);

        });
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUserRoleService.saveBatch(sysUserRoles);
        SysUser sysUser = sysUserService.getById(userId);
        sysUserService.clearUserAuthorityInfo(sysUser.getUsername());
        return Result.succ("");
    }

    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public Result repass(@RequestBody Long id) {
        SysUser user = sysUserService.getById(id);
        user.setPassword(bCryptPasswordEncoder.encode(Const.DEFAULT_PASSWORD));
        user.setUpdated(LocalDateTime.now());
        sysUserService.updateById(user);
        return Result.succ("");
    }

    @PostMapping("/updatePass")
    public Result updatePass( @Validated  @RequestBody PassDto passDto , Principal principal) {
        SysUser user = sysUserService.getByUsername(principal.getName());
        boolean matches = bCryptPasswordEncoder.matches(passDto.getCurrentPass(), user.getPassword());
        if(!matches){
            return Result.fail("旧密码不正确");
        }
        user.setPassword(bCryptPasswordEncoder.encode(passDto.getPassword()));
        user.setUpdated(LocalDateTime.now());
        sysUserService.updateById(user);
        return Result.succ("");
    }
}
